package com.study.juc.cf;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * @program: juc-study
 * @author: Zhoujian
 * @date: 2022-08-11 14:55
 * @version: 1.0
 * @description: 演示增强的功能
 **/
public class CompletableFutureDemo2 {
	public static void main(String[] args) {

		CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
			System.out.println(Thread.currentThread().getName() + "\t" + "-----come in");
			//暂停几秒钟线程
			int result = ThreadLocalRandom.current().nextInt(100);
			try {
				TimeUnit.SECONDS.sleep(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			int a = result / 0;
			System.out.println("先暂停1秒，再输出返回值" + result);

			return result;
		}).whenComplete((value,e) -> {
			if (e == null){
				System.out.println("返回值" + value);
			}
		}).exceptionally(e -> {
			e.printStackTrace();
			System.out.println("异常情况:" + e.getCause() + "\t" + e.getMessage());
			return -100;
		});
		System.out.println(Thread.currentThread().getName()+"线程开始忙其他的");

		//主线程不要立刻结束，否则CompletableFuture默认使用的线程池会立刻关闭，建议使用自己的线程池
		try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); }

	}

	private static void extracted() throws InterruptedException, ExecutionException {
		// 有返回值
		CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
			System.out.println(Thread.currentThread().getName() + "\t" + "-----come in");
			//暂停几秒钟线程
			int result = ThreadLocalRandom.current().nextInt(100);
			try {
				TimeUnit.SECONDS.sleep(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("先暂停1秒，再输出返回值" + result);

			return result;
		});

//		System.out.println(completableFuture.get());
	}
}
